<?php
/**
 * 登陆
 * @author      zlc
 * @version     1.0
 */

namespace App\Http\Controllers\Admin;

use App\Common\Logs\Logs;
use App\Common\Utill\OperationLog;
use App\Common\Utill\Utills;
use App\Models\Admin;
use App\Models\WebsitesAdmin;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Route;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    /**
     * 登录表单
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function loginForm()
    {
//        $pwd = 123456;
//        Admin::create([
//            'username'=>'测试用户',
//            'password'=>Hash::make($pwd),
//            'created_at'=>date("Y-m-d H:i:s"),
//            'updated_date'=>date("Y-m-d H:i:s"),
//            'last_ip'=>'127.0.0.1'
//        ]);
        return view('admin.login.index');
    }

    /**
     * 用于登录的字段
     * @return string
     */
    public function username()
    {
        return 'username';
    }

    /**
     * 登录成功后的跳转地址
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function redirectTo()
    {
        return route('admin.layout');
    }

    /**
     * 验证码
     * Validate the user login request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function validateLogin(Request $request)
    {
        $request->validate([
            $this->username() => 'required|string',
            'password' => 'required|string',
            'captcha' => 'required|captcha',
        ],[
            'captcha.required' => '验证码不能为空',
            'captcha.captcha' => '验证码错误',
        ]);
    }

    /**
     * 登录验证
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login(Request $request)
    {
        $this->validateLogin($request);
        $admin = Admin::where('username',$request->username)->first();
        if(!$admin){
            return back()->withErrors(['error' => ['账号不存在']]);
        }
        if($admin->is_del == -1){
            return back()->withErrors(['error' => ['账号已删除']]);
        }
        if($admin->status == 2){
            return back()->withErrors(['error' => ['账号被禁用']]);
        }
        $password = $request->input('password');
        if(!Hash::check($password,$admin->password)){
            return back()->withErrors(['password' => ['账号密码不正确']]);
        }

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if (method_exists($this, 'hasTooManyLoginAttempts') && $this->hasTooManyLoginAttempts($request)) {

            $this->fireLockoutEvent($request);
            return $this->sendLockoutResponse($request);
        }
        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }
        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    /**
     * 品达发稿点击进来
     * @param Request $request
     * @return
     */
    public function fagaoLogin(Request $request)
    {
        $orderSn = Utills::aiOrderSn();
        $referrer = $request->headers->get('referer');
        Logs::info("{$orderSn} 请求域名: ".$referrer,[],1,'fagao');
        if (!$referrer) {
           echo "非法数据";exit();
        }
        $parsedUrl = parse_url($referrer);
        $domain = isset($parsedUrl['host']) ? $parsedUrl['host'] : null;
        $allowData = [
            'www.pindaonline.com','fagao.pindarpr.com'
        ];
        if(!in_array($domain,$allowData)){
            Logs::info("{$orderSn} 非法域名:".$domain,[],1,'fagao');
            echo "非法数据";exit();
        }
        $token = $request->input("token","");
        Logs::info("{$orderSn} 请求token: ".$token,[],1,'fagao');
        if(!$token){
            echo  "非法token";exit();
        }
        //base64 前面加3个随机字符串，后面7个
        $token = substr($token,3,strlen($token)-10);
        $data = base64_decode($token);
        parse_str($data, $outputArray);
//        if(time() >= $outputArray['time'] + 3600){
//            echo  "token已失效,请返回上一个页面,点击F5刷新页面,再次点击站群管理";exit();
//        }
        $rand = $outputArray['rand_num'];
        $time = $outputArray['time'];
        $oldToken = $outputArray['token'];
        $accessKey = "u6A1wfIC8ljJGQheUGVwpY4N4eYJ7jVdADH5Z6vW";
        $serverToken = md5(md5($rand.":".$accessKey.":".$time));
        if($serverToken != $oldToken){
            Logs::info("{$orderSn} 客户端:{$outputArray['token']},服务器:{$token}",$outputArray,2,'fagao');
            echo  "token不正确";exit();
        }
        $username="品达";
        $admin = Admin::where('username',$username)->first();
        Auth::login($admin); // 登录用户
        return redirect(route('admin.layout'));
    }

    /**
     * Log the user out of the application.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        OperationLog::record(5,'用户退出');
        $this->guard()->logout();
        $request->session()->invalidate();
        return redirect(route('admin.loginForm'));
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard('admin');
    }

    /**
     * 登录成功后更新ip
     * @return void
     */
    protected function authenticated(Request $request, $user)
    {
        if ($user->status == 2) {
            $this->logout($request);
        } else {
            $user->last_ip = $request->getClientIp();
            $user->logined_at = date('Y-m-d H:i:s');
            $user->save();
        }
        OperationLog::record(4,'用户登录');
    }
}
